﻿using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

/// <summary>
/// 场景管理器
/// </summary>
public class SceneMgr : UnitySingleton<SceneMgr>
{
    [Header("场景加载设置")]
    public float minLoadingTime = 2.0f;
    public GameObject loadingScreenPrefab;

    private GameObject loadingScreen;
    private string targetScene;
    private float loadStartTime;

    /// <summary>
    /// 异步加载场景
    /// </summary>
    public void LoadSceneAsync(string sceneName)
    {
        targetScene = sceneName;
        StartCoroutine(LoadSceneCoroutine());
    }

    private IEnumerator LoadSceneCoroutine()
    {
        loadStartTime = Time.time;

        // 显示加载界面
        if (loadingScreenPrefab != null && loadingScreen == null)
        {
            loadingScreen = Instantiate(loadingScreenPrefab);
            DontDestroyOnLoad(loadingScreen);
        }

        // 开始异步加载
        AsyncOperation asyncLoad = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(targetScene);
        asyncLoad.allowSceneActivation = false;

        // 等待加载完成
        while (!asyncLoad.isDone)
        {
            float progress = Mathf.Clamp01(asyncLoad.progress / 0.9f);

            // 确保至少显示加载界面minLoadingTime秒
            if (asyncLoad.progress >= 0.9f &&
                Time.time - loadStartTime >= minLoadingTime)
            {
                asyncLoad.allowSceneActivation = true;
            }

            yield return null;
        }

        // 隐藏加载界面
        if (loadingScreen != null)
        {
            Destroy(loadingScreen);
            loadingScreen = null;
        }
    }

    /// <summary>
    /// 重新加载当前场景
    /// </summary>
    public void ReloadCurrentScene()
    {
        LoadSceneAsync(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name);
    }
}